package com.rybbaby.tss.core.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

/**
 * @description 日志文件读取工具
 * 
 * @author 谢进伟
 * 
 * @createDate 2016-1-31 上午10:33:48
 */
public class LogReadUtil {
	
	/**
	 * 读取日志(倒着读)
	 * 
	 * @param logFilePath
	 *            文件
	 * @param beginLineCount
	 *            读取行数
	 * @param lineSeparator
	 *            每一行的分隔符
	 * @return
	 */
	public static StringBuffer readLog(String logFilePath , int beginLineCount , String lineSeparator) {
		File sourceFile = new File(logFilePath);
		int totalLines = getTotalLines(sourceFile);
		// 指定读取的行号
		int lineNumber = totalLines - beginLineCount;
		lineNumber = lineNumber > totalLines ? totalLines : lineNumber;
		// 读取指定的行
		StringBuffer content = readAppointedLineNumber(sourceFile , lineNumber , lineSeparator);
		return content;
	}
	
	/**
	 * 从指定的行开始读取文件
	 * 
	 * @param sourceFile
	 *            文件
	 * @param beginLineNumber
	 *            起始行号
	 * @param lineSeparator
	 *            每一行的分隔符
	 * @return
	 */
	private static StringBuffer readAppointedLineNumber(File sourceFile , int beginLineNumber , String lineSeparator) {
		FileReader in = null;
		LineNumberReader reader = null;
		StringBuffer sb = new StringBuffer();
		try {
			in = new FileReader(sourceFile);
			reader = new LineNumberReader(in);
			String linStr = null;
			while ((linStr = reader.readLine()) != null) {
				if((reader.getLineNumber() - beginLineNumber) > 0) {
					sb.append(linStr);
					sb.append(lineSeparator);
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeResources(in , reader);
		}
		return sb;
	}
	
	/**
	 * 获取文件总行数
	 * 
	 * @param file
	 *            文件
	 * @return
	 */
	private static int getTotalLines(File file) {
		FileReader in = null;
		LineNumberReader reader = null;
		try {
			in = new FileReader(file);
			reader = new LineNumberReader(in);
			while ((reader.readLine()) != null) {
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeResources(in , reader);
		}
		return reader.getLineNumber();
	}
	
	/**
	 * 关闭相关资源
	 * 
	 * @param in
	 *            文件读取器
	 * @param reader
	 *            行级文件读取器
	 */
	private static void closeResources(FileReader in , LineNumberReader reader) {
		if(reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(in != null) {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
